<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 首页控制器
 * 
 * Enter description here ...
 * @author Administrator
 *
 */
class MemberLib  
{
    public $table_name ='member';
    
    public function __construct()
    {
        //$this->ci = & get_instance();
    }
    
    
    public function get_table_name()
    {
        return $this->table_name;
    }
    
    /**
     * 设置会话
     * Enter description here ...
     */
    public function set_session_for_name($username='')
    {
        $_SESSION['userinfo'] = array();
        $_SESSION['userid'] = '';
        $_SESSION['username'] = '';
        $_SESSION['islogin'] = 0;
        
        $ci = & get_instance();
        if ($username) {
            $sql = "select * from member where username =?";
            $query = $ci->db->query($sql, array($username)); 
            if ($query->num_rows()> 0) {
                $info = $query->row_array();
                $_SESSION['userinfo'] = $info;
                $_SESSION['userid'] = $info['id'];
                $_SESSION['username'] = $info['username'];
                $_SESSION['islogin'] = 1;
                $time = time();
                $ci->db->update(
                    $this->get_table_name(), 
                    array('last_login_at' => $time),
                    array('id' => $info['id'])
                ); 
                $_SESSION['userinfo']['last_login_at'] = $time;
                return true;
            }
        } 
        
        return false;
        
    }
    
    /**
     * 设置会话
     * Enter description here ...
     */
    public function set_session_out()
    {
        $_SESSION['userinfo'] = array();
        $_SESSION['userid'] = '';
        $_SESSION['username'] = '';
        $_SESSION['islogin'] = 0;
        
    }
    
    /**
     * 远程ip当天是否注册过
     */
    public function has_today_register($ip='')
    {
        //$ip = $_SERVER['REMOTE_ADDR'];
        $ci = & get_instance();
        $sql = "select username,real_password from member where register_ip = ? and created_at >= ?" ;
        $result = $ci->db->query($sql, array($ip, get_date_0_today()))->row();
        return $result;
        
    }
    
    /**
     * 清除48小时（因为懒得计算0点）以前的帐号
     * Enter description here ...
     */
    public function clear()
    {
        $sql = "delete from member where istest=1 and created_at < " . strval(time() - 2 * 24 * 3600 );
        $ci = & get_instance();
        $ci->db->query($sql);
        
    }
    
    public function set_auto_login($username, $password)
    {
        $ci = & get_instance();
        $username  =$ci->encrypt->decode($username);
        $sql ="select username from member where username=? and password=?";
        $member = $ci->db->query($sql, array($username, $password))->row();
        if ($member) {
            $this->set_session_for_name($member->username);
            return true;
        }   
        return false;
    }
    
}




